#include <buola/chart/cyaxis.h>

#include <buola/image/cgc.h>
#include <buola/chart/cxaxis.h>
#include <buola/chart/cxychart.h>

namespace buola { namespace chart {

CYAxis::CYAxis()
{
}

CYAxis::~CYAxis()
{
}

bool CYAxis::CanZoom()
{
    return true;
}

void CYAxis::ReduceRect(CXYChartContext &pC)
{
    if(pC.mChart->Style(CXYChart::CENTER))
    {
        pC.mRect.l+=40;
        pC.mRect.r-=40;
    }
    else
    {
        pC.mRect.l+=40;
        if(pC.mChart->Style(CXYChart::BOX))
        {
            pC.mRect.r-=5;
        }
    }
}

void CYAxis::CalcLimits(CXYChartContext &pC)
{
    mRect=pC.mRect;
    
    if(mRect.h()<0) return;

    mMapping->SetDestLimits(mRect.b-pC.mExtraSpace.b,
                           mRect.t+pC.mExtraSpace.t);

    if(mAutoScale)
    {
        mMapping->AutoScale(pC.mMinY,pC.mMinPosY,pC.mMaxY,true,35.0);
    }
}

void CYAxis::Draw(CXYChartContext &pC)
{
    bool lThin=pC.mChart->Style(CXYChart::THIN);

    if(lThin)
    {
        pC.mGC->SetLineWidth(0.8);
    }
    else
    {
        pC.mGC->SetLineWidth(1.5);
    }

    img::CColor lLinesColor(0,0,0);
    lLinesColor.a=0.2;

    std::vector<double> lTicks;
    int lExp=mMapping->GetTicks(lTicks,35.0);
    double lExpMult=pow(10,lExp);

    for(int i=0;i<lTicks.size();i++)
    {
        if(std::abs(lTicks[i])<1e-10)
            lTicks[i]=0;

        double lYPos=Map(lTicks[i]);

        if(lThin)
            lYPos=round(lYPos-0.5)+0.5;
        
        bool lRightTicks=pC.mChart->Style(CXYChart::BOX);
        
        pC.mGC->SetSource(img::CColor(0,0,0));
        pC.mGC->Path().MoveTo(CPoint_d(mRect.l,lYPos));
        pC.mGC->Path().LineTo(CPoint_d(mRect.l+7,lYPos));
        pC.mGC->StrokePath();
        
        if(lRightTicks)
        {
            pC.mGC->Path().MoveTo(CPoint_d(mRect.r-7,lYPos));
            pC.mGC->Path().LineTo(CPoint_d(mRect.r,lYPos));
            pC.mGC->StrokePath();
        }

        pC.mGC->DrawText(CPoint_d(mRect.l-4,lYPos),to_wstring(lTicks[i]/lExpMult),img::ETextPos::RIGHT|img::ETextPos::VCENTER);

        pC.mGC->SetLineStyle(img::ELineStyle::ONOFF);
        pC.mGC->SetSource(lLinesColor);
        pC.mGC->Path().MoveTo(CPoint_d(mRect.l+7,lYPos));
        pC.mGC->Path().LineTo(CPoint_d(lRightTicks?(mRect.r-7):mRect.r,lYPos));
        pC.mGC->StrokePath();
        pC.mGC->SetLineStyle(img::ELineStyle::SOLID);
    }

    if(mTitle.length()||lExp!=0)
    {
        std::wstring lTitle=mTitle;
        if(lExp!=0)
        {
            lTitle+=L" (x10^";
            lTitle+=to_wstring(lExp);
            lTitle+=L")";
        }
    
        pC.mGC->SetSource(img::CColor(0,0,0));
//        pC.mGC->PushState();
        pC.mGC->Translate(CPoint_d(mRect.l-30,(mRect.t+mRect.b)/2.0));
        pC.mGC->Rotate(-M_PI/2);
        pC.mGC->DrawText(CPoint_d(0,0),lTitle,img::ETextPos::CENTER);
//        pC.mGC->PopState();
    }
}

/*namespace chart*/ } /*namespace buola*/ }
